package com.rr.mymoney.jsf;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.rr.mymoney.bo.CategoryBo;
import com.rr.mymoney.bo.UserBo;
import com.rr.mymoney.model.User;

// Spring instantiates the object, so there is no use for JSF annotations
@Controller
@Scope("view")
public class UsersController extends AbstractController {

    private static final long serialVersionUID = 3034287104359142441L;

    private static transient Logger log = Logger.getLogger(UsersController.class);

    private transient UserBo userBo;
    private transient CategoryBo categoryBo;

    private List<User> users;
    private User selectedUser;
    private User user = new User();

    /**
     * @param userBo
     *            the userBo to set
     */
    @Autowired
    public void setUserBo(UserBo userBo) {
	this.userBo = userBo;
    }

    /**
     * @param categoryBo
     *            the categoryBo to set
     */
    @Autowired
    public void setCategoryBo(CategoryBo categoryBo) {
	this.categoryBo = categoryBo;
    }

    public List<User> getUsers() {
	return userBo.getAll();
    }

    public User getSelectedUser() {
	return selectedUser;
    }

    public void setSelectedUser(User selectedUser) {
	this.selectedUser = selectedUser;
    }

    public User getUser() {
	return user;
    }

    public void setUser(User user) {
	this.user = user;
    }

    public void saveUser() {
	log.debug("save user: " + user.toString());
	try {
	    userBo.saveOrUpdate(user);
	} catch (Exception e) {
	    log.error("Error saving user: ", e);
	    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Save", e.getMessage());
	    FacesContext.getCurrentInstance().addMessage(null, message);
	}
    }

    public void updateUser() {
	log.debug("update user: " + selectedUser.toString());
	try {
	    userBo.saveOrUpdate(selectedUser);
	} catch (Exception e) {
	    log.error("Error updating user: ", e);
	    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Update", e.getMessage());
	    FacesContext.getCurrentInstance().addMessage(null, message);
	}
    }

    public void deleteUser() {
	try {
	    log.debug("delete user: " + selectedUser.toString());
	    userBo.delete(selectedUser);
	} catch (Exception e) {
	    log.error("Error on delete: ", e);
	    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Delete", e.getMessage());
	    FacesContext.getCurrentInstance().addMessage(null, message);
	}
    }

}
